package scl90

import (
	"Student_Mental/DBconfing"
	"Student_Mental/model"
	"bufio"
	"bytes"
	"encoding/json"
	"fmt"
	"github.com/gin-gonic/gin"
	"net/http"
	"strconv"
	"strings"
	"time"
)

func GetScl90(c *gin.Context) {
	pageStr := c.Query("page")
	limitStr := c.Query("limit")

	page, err := strconv.Atoi(pageStr)
	if err != nil || page < 1 {
		page = 1
	}

	limit, err := strconv.Atoi(limitStr)
	if err != nil || limit < 1 {
		limit = 10 // 默认每页显示10条记录
	}

	offset := (page - 1) * limit
	var Scl90List []model.SCL90
	sqlDb, err := DBconfing.Mysql()
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{
			"code":    http.StatusInternalServerError,
			"message": "Failed to connect to the database",
		})
		return
	}
	defer sqlDb.Close()
	var count int
	sqlDb.QueryRow("SELECT count(*) FROM scl90").Scan(&count)
	rows, err := sqlDb.Query("SELECT * FROM scl90 LIMIT ? OFFSET ?", limit, offset)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{
			"code":    http.StatusInternalServerError,
			"message": "Failed to execute the query",
		})
		return
	}
	defer rows.Close()

	for rows.Next() {
		var scl90 model.SCL90
		err := rows.Scan(
			&scl90.ID,
			&scl90.UserID,
			&scl90.Somatization,
			&scl90.ObsessiveCompulsive,
			&scl90.InterpersonalSensitivity,
			&scl90.Depression,
			&scl90.Anxiety,
			&scl90.Hostile,
			&scl90.Terror,
			&scl90.Bigotry,
			&scl90.Psychotic,
			&scl90.Other,
			&scl90.Sum,
			&scl90.Average,
			&scl90.Feminine,
			&scl90.MasculineSum,
			&scl90.Masculine,
			&scl90.MasculineAge,
			&scl90.TextId,
		)
		sqlDb.QueryRow("(SELECT student_name FROM student WHERE id = ?)", scl90.UserID).Scan(&scl90.StudentName)
		if err != nil {
			c.JSON(http.StatusInternalServerError, gin.H{
				"code":    http.StatusInternalServerError,
				"message": "Failed to scan row data",
			})
			return
		}

		Scl90List = append(Scl90List, scl90)
	}

	c.JSON(http.StatusOK, gin.H{
		"code":  0,
		"count": count,
		"data":  Scl90List,
	})
}

func GetScl90ByUserID(c *gin.Context) {
	userID := c.PostForm("userID")

	sqlDb, err := DBconfing.Mysql()
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{
			"code":    http.StatusInternalServerError,
			"message": "Failed to connect to the database",
		})
		return
	}
	defer sqlDb.Close()

	var scl90 model.SCL90
	err = sqlDb.QueryRow("SELECT * FROM scl90 WHERE Id = ?", userID).Scan(
		&scl90.ID,
		&scl90.UserID,
		&scl90.Somatization,
		&scl90.ObsessiveCompulsive,
		&scl90.InterpersonalSensitivity,
		&scl90.Depression,
		&scl90.Anxiety,
		&scl90.Hostile,
		&scl90.Terror,
		&scl90.Bigotry,
		&scl90.Psychotic,
		&scl90.Other,
		&scl90.Sum,
		&scl90.Average,
		&scl90.Feminine,
		&scl90.MasculineSum,
		&scl90.Masculine,
		&scl90.MasculineAge,
		&scl90.TextId,
	)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{
			"code":    http.StatusInternalServerError,
			"message": "Failed to execute the query or scan row data",
		})
		return
	}

	err = sqlDb.QueryRow("SELECT student_name FROM student WHERE id = ?", scl90.UserID).Scan(&scl90.StudentName)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{
			"code":    http.StatusInternalServerError,
			"message": "Failed to retrieve student name",
		})
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"code": 0,
		"data": scl90,
	})
}

func GptReports(c *gin.Context) {
	dataMapJSON := c.PostForm("dataMapJSON")
	gPTSendMsgText := GetGpt(dataMapJSON)
	c.JSON(http.StatusOK, gin.H{
		"code": 0,
		"data": gPTSendMsgText,
	})
}

func GetGpt(userContext string) string {
	var chatGPTMsgs []*model.ChatGPTMessage
	//模仿用户第一次选择
	chatGPTMsgs = append(chatGPTMsgs, &model.ChatGPTMessage{
		Role:    "system",
		Content: "你是一位医学专家，学生向你展示了他们的 SCL-90 测评结果。SCL-90 是一种常用的心理健康测评工具，用于评估一个人在不同心理领域的症状和问题。作为专家，请使用你的专业知识和经验，以 ChatGPT 的身份提供建议，帮助这位学生解读他们的 SCL-90 测评结果，并提供适当的建议以改善他们的心理健康。并且评估因子分数高于2分的几个因子，给出相应的改善措施，回答不要超过300个字\n回答的格式：\n根据学生的scl-90测评结果。下面是对每个测试因子的评估和相应的建议：\n这里写建议\n总的来说：",
	})
	chatGPTMsgs = append(chatGPTMsgs, &model.ChatGPTMessage{
		Role:    "assistant",
		Content: "您好，请你告诉我你的测试结果？",
	})
	chatGPTMsgs = append(chatGPTMsgs, &model.ChatGPTMessage{
		Role:    "user",
		Content: "这是scl90结果:" + userContext,
	})
	var err error
	gPTSendMsg := &model.SendMessage{
		MsgType:      "Gpt",
		OpenInputBox: true,
		OpenChatGPT:  true,
		SendTime:     time.Now().Unix(),
		UserID:       "df4619281a7827624a5ebbc49f923659",
	}
	gPTSendMsg, _, err, _ = GetGPTAnswerStreamTest(chatGPTMsgs, gPTSendMsg)
	if err != nil {
		fmt.Println(err)
	}

	return gPTSendMsg.Text
}

func GetGPTAnswerStreamTest(chatGPTMsgs []*model.ChatGPTMessage, message *model.SendMessage) (*model.SendMessage, bool, error, string) {
	needRefreshFlag := false
	currentTime := time.Now().Unix()
	url := "http://dcdn.mate.dianshihome.com/api/ask2gptV2"
	getGPTAnswerReq := model.ChatCompletionReq{
		Model:       "gpt-3.5-turbo",
		Messages:    chatGPTMsgs,
		MaxTokens:   2048,
		Temperature: 0.1,
		TopP:        0.1,
		Stream:      true,
	}
	paramsBytes, _ := json.Marshal(getGPTAnswerReq)
	req, err := http.NewRequest(http.MethodPost, url, bytes.NewReader(paramsBytes))
	if err != nil {
		fmt.Println(err)
	}
	req.Header.Set("Content-Type", "application/json")
	client := &http.Client{}
	resp, err := client.Do(req)
	if err != nil {
		fmt.Println(err)
	}
	scanner := bufio.NewScanner(resp.Body)
	for scanner.Scan() {
		line := scanner.Text()
		if strings.HasPrefix(line, "data: ") {
			chatTextResp := &model.ChatCompletionsStreamResp{}
			// 处理完整聊天文本
			chatText := strings.TrimSpace(strings.TrimPrefix(line, "data: "))
			if chatText == "[DONE]" {
				//gPTSendMsg := &model.SendMessage{
				//	MsgType:      "Gpt",
				//	OpenInputBox: true,
				//	OpenChatGPT:  true,
				//	SendTime:     currentTime,
				//	GptMsgType:   4,
				//	UserID:       "df4619281a7827624a5ebbc49f923659",
				//}
				//sendMsgBytes, _ := json.Marshal(gPTSendMsg)
				//str := string(sendMsgBytes)
				//fmt.Println(str)
				break
			}
			json.Unmarshal([]byte(chatText), chatTextResp)
			if chatTextResp.Choices[0].Message.Content == "" {
				continue
			}
			gPTSendMsg := &model.SendMessage{
				MsgType:      "Gpt",
				OpenInputBox: true,
				OpenChatGPT:  true,
				SendTime:     currentTime,
				GptMsgType:   2,
				Text:         chatTextResp.Choices[0].Message.Content,
				UserID:       "df4619281a7827624a5ebbc49f923659",
			}
			message.Text += chatTextResp.Choices[0].Message.Content
			if chatTextResp.Choices[0].FinishReason == "length" {
				chatGPTMsgs = append(chatGPTMsgs, &model.ChatGPTMessage{
					Role:    "assistant",
					Content: message.Text,
				})

				_, _, err, text := GetGPTAnswerStreamTest(chatGPTMsgs, gPTSendMsg)
				if err != nil {
					return nil, needRefreshFlag, err, text
				}
			}
			if chatTextResp.Choices[0].FinishReason == "max_tokens" {
				needRefreshFlag = true
				return nil, needRefreshFlag, err, message.Text
			}
			//fmt.Print(gPTSendMsg.Text)
		}
	}
	return message, needRefreshFlag, err, message.Text
}
